<?php
namespace app\index\controller;

use app\interfaces\model\Coupon as CouponModel;
use app\interfaces\model\MemberCoupon as MemberCouponModel;
use think\Request;
use think\Exception;
use think\Db;
use think\Loader;

class Coupon
{

    /**
     * 创建赠送的优惠券
     */
    public function send($role_id = 3,$member_id = 35)
    {
        $coupon_data = Db::name('coupon')->where('system', 1)->where('role_id', $role_id)->where('auding_status', 2)->where('status', 1)->select();
//        halt($coupon_data); //2被邀请人 3注册会员
        if(!empty($coupon_data)){
            $varvalue3 = Db::name('config')->where('varname','web_conpon_time')->value('varvalue');//注册优惠券的有效天数
            $varvalue2 = Db::name('config')->where('varname','web_conpon_time2')->value('varvalue');//被邀请注册优惠券的有效天数
            $end_time = time()+60*24*60*100;
            if($role_id == 2){
                $end_time = $varvalue2*60*24*60+time();
            }
            if($role_id == 3){
                $end_time = $varvalue3*60*24*60+time();
            }
            foreach ($coupon_data as $k => $v){
                $single = $v['single_id'];
                if($v['type'] == 4){
                        $single = $v['single_id'] == 0 ? 0 : ','.$v['single_id'].',';
                }
                $data = [
                    'type' => $v['type'],
                    'single_id' => $single,
                    'auding_status' => 2,
                    'member_id' => $member_id,
                    'coupon_id' => $v['id'],
                    'title' => $v['title'],
                    'minus_price' => $v['actual_price'],
                    'total_price' => $v['virtual_price'],
                    'content' => $v['content'],
                    'start_time' => time(),
                    'end_time' => $end_time,
                    'status' => $v['status'],
                    'create_time' => time()
                ];
                Db::name('member_coupon')->insert($data);
            }
        }
    }

    public function zz(){
        Loader::import('alipay.AopSdk');
        $aop = new \AopClient ();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = 'your app_id';
        $aop->rsaPrivateKey = '请填写开发者私钥去头去尾去回车，一行字符串';
        $aop->alipayrsaPublicKey='请填写支付宝公钥，一行字符串';
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='GBK';
        $aop->format='json';
        $request = new AlipayFundTransToaccountTransferRequest ();
        $request->setBizContent("{" .
            "\"out_biz_no\":\"3142321423432\"," .
            "\"payee_type\":\"ALIPAY_LOGONID\"," .
            "\"payee_account\":\"abc@sina.com\"," .
            "\"amount\":\"12.23\"," .
            "\"payer_show_name\":\"上海交通卡退款\"," .
            "\"payee_real_name\":\"张三\"," .
            "\"remark\":\"转账备注\"" .
            "}");
        $result = $aop->execute ( $request);

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode)&&$resultCode == 10000){
            echo "成功";
        } else {
            echo "失败";
        }
    }
    /*
     * 用户端 - 领取平台优惠券列表
     * @param  string $type_id 会员ID
     */
    public function coupon_index()
    {
        // 获取参数
        $type_id = Request::instance()->param('type_id');
        $user_id = Request::instance()->param('user_id');

        if (empty($type_id) || empty($user_id)) throw new Exception('not Empty');

        $model = new CouponModel();

        $result = $model->where(['member_id' => '0', 'parenTid' => $type_id, 'status' => '1', 'end_time' => ['gt', time()]])
            ->field('id,title,actual_price,virtual_price,number,sort as receive_status')
            ->order(['sort' => 'desc'])
            ->paginate(6);

        return ['code' => 200, 'message' => '成功', 'data' => $result];
    }

    /*
     * 用户端 - 领取店铺优惠券列表
     * @param  string $shop_id 店铺ID
     * @param  string $user_id 会员ID
     */
    public function coupon_list()
    {
        // 获取参数
        $shop_id = Request::instance()->param('shop_id');

        if (empty($shop_id)) throw new Exception('not Empty');

        $model = new CouponModel();

        $result = $model->where(['member_id' => $shop_id, 'status' => '1', 'end_time' => ['gt', time()]])
            ->field('id,title,actual_price,virtual_price,number,content,start_time,end_time,sort as receive_status')
            ->order(['sort' => 'desc'])
            ->paginate(6);

        return ['code' => 200, 'message' => '成功', 'data' => $result];
    }

    /*
     * 用户端 - 领取优惠券
     * @param  string $user_id      会员ID
     * @param  string $coupon_id    优惠券ID
     */
    public function get_coupon()
    {
        // 获取参数
        $user_id = Request::instance()->param('user_id');
        $coupon_id = Request::instance()->param('coupon_id');

        if (empty($coupon_id) || empty($user_id)) throw new Exception('not Empty');

        // 读取优惠券信息
        $find = CouponModel::where(['id' => $coupon_id])->find();

        // 查询自己的优惠券
        $model = new MemberCouponModel();

        // 查询是否领取过
        $id = $model->where(['coupon_id' => $coupon_id, 'member_id' => $user_id])->value('id');

        // 判断失败状态
        if ($user_id == $find['member_id']) return ['code' => 402, 'message' => '不能领取自己的优惠券'];

        if ($find['number'] <= '0') return ['code' => 402, 'message' => '优惠券已被领完,下次要早点哦'];

        if (!empty($id)) return ['code' => 402, 'message' => '您已经领取过该优惠券'];

        $data = [
            'member_id'     => $user_id,
            'shop_id'       => $find['member_id'],
            'coupon_id'     => $coupon_id,
            'title'         => $find['title'],
            'actual_price'  => $find['actual_price'],
            'virtual_price' => $find['virtual_price'],
            'content'       => $find['content'],
            'start_time'    => strtotime($find['start_time']),
            'end_time'      => strtotime($find['end_time']),
            'status'        => '2',
            'create_time'   => time()
        ];

        $result = $model->save($data);

        // 优惠券数量减一

        Db::name('Coupon')->where('id', $coupon_id)->setDec('number', 1);

        if ($result) {
            return ['code' => 200, 'message' => '成功'];
        }

        return ['code' => 401, 'message' => '网络繁忙'];

    }
}
